/* entity */
import Field, { FieldComponent } from '@model/entity/Field'
/* service */
import FieldService, { getFieldFormType, getFieldName } from '@service/FieldService'
import Log from '@src/util/log'
/* vue */
import Vue, { VueConstructor } from 'vue'

import { useNewVue } from '@hooks/useNewVue'
const { createVue } = useNewVue();

/**
 * @description 获取空的vue实例
 * @return {VueConstructor<Vue>} vue实例
 */
function getEmptyVueInstance(): VueConstructor<Vue> {
  return createVue({}) as VueConstructor<Vue>
}

/**
 * @description 获取表单字段组件对象
 * @param {Field} field 表单字段
 * @return {FieldComponent} 表单组件对象
 */
export function getFormComponent(field: Field): FieldComponent {
  if (field?.component) return field.component
  
  return {
    setting: getEmptyVueInstance(),
    preview: getEmptyVueInstance(),
    build: getEmptyVueInstance(),
    view: getEmptyVueInstance(),
    extend: {}
  }
}

/**
 * @description 获取字段对应的搜索组件
 * @param {Field} field 字段数据
 * @return {VueConstructor<Vue>} 搜索组件
 */
export function getFieldSearchComponent(field: Field): VueConstructor<Vue> {
  const component: FieldComponent = getFormComponent(field)
  const formType: string = getFieldFormType(field)
  const fieldName: string = getFieldName(field)
  
  // 优先获取 【字段类型】 + 【字段名称】 搜索的组件
  const formTypeAndFieldNameSearchComponent: VueConstructor<Vue> | undefined = component?.extend?.[`${formType}_${fieldName}_search`]
  if (formTypeAndFieldNameSearchComponent) return formTypeAndFieldNameSearchComponent
  
  // 此获取 【字段类型】 搜索的组件
  const formTypeSearchComponent: VueConstructor<Vue> | undefined = component.extend?.[`${formType}_search`]
  if (formTypeSearchComponent) return formTypeSearchComponent
  
  // 默认返回构建对应的组件
  return component.build
}

/** 
 * @description 表单提交数据处理方法
 * @param {Field[]} fields 表单字段数据
 * @param {Record<string, any>} formData 表单数据
 * @param {Boolean} isAttribute 是否有自定义属性
 * @return {Record<string, any>} 处理后的表单数据
*/
export function formSubmissionDataProcessingHandler<T extends Record<string, any>>(
  fields: Field[], 
  formData: T,
  isAttribute: boolean = false
): T {
  try {
    
    // 1. 过滤隐藏字段对应的值
    let filteredHiddenFieldsFormData = FieldService.hiddenFieldValueFilterHandler<T>(fields, formData, isAttribute)
    
    return filteredHiddenFieldsFormData
    
  } catch (error) {
    
    Log.error(error, formSubmissionDataProcessingHandler.name)
    
    return formData
  }
}

export default {
  getFieldSearchComponent,
  formSubmissionDataProcessingHandler
}
